import {BaseUrl} from "./NetConfig";
import {log} from "./Log";

export class StockNet {
    /**
     * 请求头
     */
    header = {};

    /**
     * function: 根据需求处理请求参数：添加固定参数配置等
     * @params 请求参数
     */
    dealParams(params) {
        log("请求参数:", params)
        return params;
    }

    get(path, params = {}, isShowLoading = false) {
        log("请求方式：", "GET")
        return this.request(path, params, "GET", isShowLoading);
    }

    /**
     * 供外部post请求调用
     */
    post(path, params = {}, isShowLoading = false) {
        log("请求方式：", "POST")
        return this.request(path, params, "POST", isShowLoading);
    }

    /**
     * function: 封装网络请求
     * @url URL地址
     * @params 请求参数
     * @method 请求方式：GET/POST
     * @onSuccess 成功回调
     * @onFailed  失败回调
     */

    request(path, params, method, isShowLoading) {
        var url = BaseUrl + path;
        if (isShowLoading)
            wx.showLoading({
                title: "正在加载中...",
            });
        params = this.dealParams(params);
        var header = this.header;
        return new Promise(function (resolve, reject) {
            wx.request({
                url: url,
                data: params,
                method: method,
                header: header,
                success: function (res) {
                    wx.hideLoading();
                    if (res.statusCode == 200 && res.data) {
                        resolve(res.data); //request success
                    } else {
                        reject(res); //request failed
                    }
                },
                fail: function (error) {
                    wx.hideLoading();
                    reject({code: 50001, message: "服务器错误,请联系服务端开发处理，查看路径和host"});
                }
            })
        });
    }
}
